package user

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"time"
	//"github.com/bitly/go-simplejson"
	"github.com/gin-gonic/gin"
	//"github.com/xlstudio/wxbizdatacrypt"
	"net/http"
	"zhuandan/data_source"
	"zhuandan/models"
)

func UserLoginyyb(ctx *gin.Context) {
	json1 := KDRespBody{}
	ctx.ShouldBind(&json1)
	code := json1.Code
	laiyuan := json1.Laiyuan

	open := Accesstoken2(code)
	openid := open.Openid
	unionid := open.Unionid
	if openid == "" {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    300,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "账号不存在",
		})
		return
	}

	reqip := ctx.ClientIP()
	var user models.Useryyb
	data_source.Db.Where("routine_openid = ?", openid).First(&user)

	if user.ID > 0 {
		upuser := models.Useryyb{
			LoginTime: time.Now().Unix(),
			LoginIp:   reqip,
			LoginNum:  user.LoginNum + 1,
		}
		data_source.Db.Where("routine_openid = ?", openid).Updates(upuser)
	} else {
		if unionid == "" {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    300,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "账号不存在",
			})
			return
		}
		xq := Userinfohq(open.AccessToken, openid)
		adduser := models.Useryyb{
			LoginTime:     time.Now().Unix(),
			LoginIp:       reqip,
			RoutineOpenid: openid,
			CreateTime:    time.Now().Unix(),
			LoginNum:      1,
			Logo:          xq.Headimgurl,
			Nickname:      xq.Nickname,
			Unionid:       unionid,
			Laiyuan:       laiyuan,
		}
		data_source.Db.Create(&adduser)
	}
	var userinfo models.User
	data_source.Db.Where("routine_openid = ?", openid).First(&userinfo)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    userinfo,
		"msg":     "ok",
	})
	return
}

type ResponseUserinfohq struct {
	Nickname   string `json:"nickname"`
	Headimgurl string `json:"headimgurl"`
}

func UserLoginyybcs(ctx *gin.Context) {
	token := Accesstoken()
	fmt.Println(token)
	xq := Userinfohq(token, "oHQFC0Tm7oR8zWr46oaMFqLhTJZM")
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    xq,
		"msg":     "ok",
	})
	return
}
func Userinfohq(token, openid string) (data ResponseUserinfohq) {
	//fmt.Println("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + openid + "&lang=zh_CN")
	resp, err := http.Get("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + openid + "&lang=zh_CN")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := ResponseUserinfohq{}
	fmt.Println(string(body), "-------------------")

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}
